<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled" class="position-icon">
      <a-form-model ref="form" :rules="rules" :model="model" slot="detail">
        <a-row>
          <div class="left-sidebar">
            <div class="icon-styly">
              <a-icon type="container"/>
            </div>
            <div class="vh-line vh-jbline"></div>
          </div>
          <div class="title">基本信息</div>
          <a-col :span="24">
            <a-form-model-item label="模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入模板名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="模板类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag placeholder="请选择模板类型" v-model="model.type" dictCode="template_type"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="批次名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportPeriod">
              <a-input v-model="model.reportPeriod" placeholder="请输入批次名称"></a-input>
<!--              <j-dict-select-tag
                placeholder="请选择模报告期"
                v-model="model.reportPeriod"
                dictCode="template_report_type"
              />-->
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="审计类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportType">
              <j-dict-select-tag placeholder="请选择审计类型" v-model="model.reportType" dictCode="report_type"/>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">
            <a-form-model-item label="初始版本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="version">
              <a-input
                addon-before="V"
                type="Number"
                :step="0.1"
                :min="1"
                v-model="model.version"
                placeholder="请输入模板版本"
              />
            </a-form-model-item>
          </a-col>-->
<!--          <a-col :span="24">
            <a-form-model-item label="报表分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportCategoryId">
              <a-select v-model="model.reportCategoryId" placeholder="报表分类">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu"/>
                  <a-divider style="margin: 4px 0;"/>
                  <div
                    style="padding: 4px 8px; cursor: pointer;"
                    @mousedown="e => e.preventDefault()"
                    @click="addItem('report')"
                  >
                    <a-icon type="plus"/>
                    新增
                  </div>
                </div>
                <a-select-option v-for="(item, index) in reportList" :value="item.id || ''" :label="item.name"
                                 :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="报表类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskCategoryId">
              <a-select v-model="model.taskCategoryId" placeholder="请选择报表类型">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu"/>
                  <a-divider style="margin: 4px 0;"/>
                  <div
                    style="padding: 4px 8px; cursor: pointer;"
                    @mousedown="e => e.preventDefault()"
                    @click="addItem('task')"
                  >
                    <a-icon type="plus"/>
                    新增
                  </div>
                </div>
                <a-select-option v-for="(item, index) in taskList" :value="item.id || ''" :label="item.name"
                                 :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <div class="left-sidebar">
            <div class="icon-styly icon-color-yellow">
              <a-icon type="folder"/>
            </div>
            <div class="vh-line vh-wjline vh-line-yellow"></div>
          </div>
          <div class="title color-yellow">上传文件</div>
          <a-col :span="24" class="uploadBox" style="margin-left: 67px">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol1" style="margin-bottom: 10px">
              <div class="add-class" @click="fileViewShow = true">
                <a-icon type="plus"/>
                <span>点击上传</span>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" class="fileList" style="margin-left: 67px">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol1">
              <a-table
                v-if="tableShow"
                ref="table"
                size="default"
                rowKey="uid"
                :columns="columns"
                :pagination="false"
                :dataSource="model.uploadmodel"
                class="file-table"
              >
                <template slot="icon" slot-scope="text, record">
                  <img :src="fileIcon" alt=""/>
                </template>
                <template slot="name" slot-scope="text, record">
                  <j-ellipsis :value="text" :length="30"/>
                </template>
                <span slot="action" slot-scope="text, record">
                  <a-button @click="OnPerview(record)" type="link" title="预览"> <a-icon type="eye"/></a-button>
                  <a-button @click="OnDownLoad(record)" type="link" title="下载">
                    <a-icon type="vertical-align-bottom"
                    /></a-button>
                  <a-button @click="OnRemove(record)" type="link" title="删除">
                    <a-icon type="close" style="color: red"
                    /></a-button>
                </span>
              </a-table>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <div class="left-sidebar">
            <!-- <div class="vh-line vh-wcline"></div> -->
            <div class="icon-styly icon-color-gray">
              <a-icon type="check-circle"/>
            </div>
          </div>
          <div class="title color-gray">创建完成</div>
        </a-row>
      </a-form-model>
    </j-form-container>
    <j-modal
      title="文件上传"
      width="480px"
      :visible="fileViewShow"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <fileUpload ref="fileUpload"></fileUpload>
    </j-modal>
    <a-modal
      :title="addModalType.name + '类别'"
      :visible="addShow"
      @ok="OnAdd"
      @cancel="addShow = false"
    >
      <p>类别名称：</p>
      <a-input
        v-model="categoryName"
        placeholder="请输入类别名称"
      />
    </a-modal>
  </a-spin>
</template>

<script>
  import fileIcon from '../../icon/file.png'
  import fileUpload from '@/views/sj/components/fileUpload'
  import {deleteAction, getAction, httpAction} from '@/api/manage'
  import {Base64} from 'js-base64'

  const columns = [
    {
      title: 'icon',
      width: 30,
      align: 'right',
      dataIndex: 'icon',
      scopedSlots: {customRender: 'icon'},
      key: 'icon',
    },
    {
      title: '文件名',
      align: 'left',
      dataIndex: 'name',
      scopedSlots: {customRender: 'name'},
      key: 'name',
    },
    {
      title: '操作',
      align: 'right',
      dataIndex: 'action',
      width: 120,
      slots: {title: 'actionName'},
      scopedSlots: {customRender: 'action'},
    },
  ]
  export default {
    name: 'CreateForm',
    components: {
      fileUpload,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      },
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
    },
    data() {
      return {
        addShow: false,
        categoryName: '',
        fileIcon: fileIcon,
        model: {},
        reportList: [],
        taskList: [],
        rules: {
          name: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '必填项', trigger: 'change'}
          ],
          reportPeriod: [
            {required: true, message: '必填项', trigger: 'change'}
          ],
          /*reportType: [
            {required: true, message: '必填项', trigger: 'change'}
          ],*/
          /*version: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],*/
          /*reportCategoryId: [
            {required: true, message: '必填项', trigger: 'change'}
          ],*/
          taskCategoryId: [
            {required: true, message: '必填项', trigger: 'change'}
          ],
        },
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        labelCol1: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol1: {
          xs: {span: 24},
          sm: {span: 19},
        },
        confirmLoading: false,
        url: {
          add: '/sjtb/dataCollectionTemplateInfo/add',
          edit: '/sjtb/dataCollectionTemplateInfo/edit',
          reportList: '/sjtb/dataCollectionReportCategory/list',
          taskList: '/sjtb/dataCollectionTaskCategory/list',
        },
        fileViewShow: false,
        tableShow: false,
        columns: columns,
        addModalType:{},
        addModalTypeCategory: {
          report: {
            name: '报表分类',
            url: '/sjtb/dataCollectionReportCategory/add',
            refreshMethod: 'getReportList'
          },
          task: {
            name: '报表类型',
            url: '/sjtb/dataCollectionTaskCategory/add',
            refreshMethod: 'getTaskList'
          }
        } // 新建类别类型
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    watch: {
      $route: {
        handler: function (to) {
          if (to.path === '/sjcj/mbgl/mbsj/hz') {
            this.model.reportType = 1
          } else if (to.path === '/sjcj/mbgl/mbsj/tb') {
            this.model.reportType = 0
          }
        },
        immediate: true
      },
      'model.uploadmodel': {
        handler: function (val) {
          if (val) {
            this.tableShow = val.length > 0
          }
        },
        immediate: true,
      },
    },
    created() {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model))
    },
    methods: {
      OnAdd() {
        const { url, refreshMethod } = this.addModalType; // 假设 modalType 是当前选择的类型
        httpAction(url, {name: this.categoryName}, 'post').then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.addShow = false
            this.categoryName = ''
            this[refreshMethod]();
            this.addModalType = {}
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      addItem(category) {
        this.addModalType = this.addModalTypeCategory[category]
        this.categoryName = ''
        this.addShow = true
      },
      handleOk() {
        let data = this.$refs.fileUpload.fileData()
        if (this.model.uploadmodel) {
          this.model.uploadmodel = [...this.model.uploadmodel, ...data]
        } else {
          this.model.uploadmodel = [...data]
        }
        this.model = Object.assign({}, this.model)
        this.fileViewShow = false
      },
      handleCancel() {
        this.$refs.fileUpload.fileClear()
        this.fileViewShow = false
      },
      getReportList() {
        getAction(this.url.reportList).then((res) => {
          if (res.success && res.result.length > 0) {
            this.reportList = res.result
          } else {
            console.log(res)
          }
        })
      },

      getTaskList() {
        getAction(this.url.taskList).then((res) => {
          if (res.success && res.result.length > 0) {
            this.taskList = res.result
          } else {
            console.log(res)
          }
        })
      },
      add() {
        this.edit(this.modelDefault)
        this.model.version = 1
        this.getReportList()
        this.getTaskList()
      },
      edit(record) {
        this.model = Object.assign({}, record)
        this.visible = true
      },

      OnPerview(record) {
        let fileUrl = `${window._CONFIG['onlinePreviewFileURL']}/sys/common/static${record.path}`
        // let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(fileUrl)}`
        let url = `${window._CONFIG['onlinePreviewDomainURL']}?url=${encodeURIComponent(Base64.encode(fileUrl))}`
        window.open(url, '_blank')
      },
      OnDownLoad(record) {
        this.$message.success('正在下载，请稍等！')
        let url = `${window._CONFIG['domianURL']}/sys/common/static/${record.path}`
        window.open(url, '_blank')
      },
      OnRemove(record) {
        let fileArr = [...this.model.uploadmodel]
        if (record.path) {
          this.ApiDel(record, {url: record.path})
        }
        for (let item of fileArr) {
          if (record.uid === item.uid) {
            const index = fileArr.indexOf(item)
            fileArr.splice(index, 1)
          }
        }
        this.model.uploadmodel = fileArr
        this.model = Object.assign({}, this.model)
      },
      ApiDel(record, path) {
        deleteAction('/sjtb/dataCollectionTemplateInfo/deleteFile', path).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      submitForm() {
        const that = this
        // 触发表单验证
        this.$refs.form.validate((valid) => {
          if (valid) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let data = JSON.parse(JSON.stringify(this.model))
            if (data.uploadmodel && data.uploadmodel.length > 0) {
              for (let item of data.uploadmodel) {
                delete item.file
                delete item.status
                delete item.uid
              }
            } else {
              that.$message.warning('请上传文件')
              that.confirmLoading = false
              return
            }
            httpAction(httpurl, data, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        })
      },
    },
  }
</script>
<style scoped lang="less">
  .file-table {
    /deep/ .ant-btn-link {
      padding: 0 5px !important;
    }

    /deep/ .ant-table-thead {
      display: none;
    }

    /deep/ .ant-table-tbody {
      tr {
        width: 100%;
        margin-bottom: 5px !important;

        td {
          padding: 0 5px;
          background-color: #f5f5f5;
          border: 0;
        }
      }
    }
  }

  .title {
    width: 19.5%;
    text-align: right;
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 15px;
    color: #3955a5;
  }

  .add-class {
    cursor: pointer;
    border-radius: 10px;
    height: 70px;
    width: 65px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: #dfe2fc;
    align-items: center;

    i {
      font-size: 22px;
      color: #3955a5;
    }

    span {
      font-size: 12px;
      line-height: 20px !important;
      color: #3955a5;
    }
  }

  .position-icon {
    position: relative;

    .left-sidebar {
      position: absolute;
      top: -4px;
      left: 14px;
      width: 40px;
      height: 100%;
    }

    .icon-styly {
      width: 30px;
      height: 30px;
      background-color: #3955a5;
      color: white;
      text-align: center;
      vertical-align: middle;
      font-size: 20px;
      border-radius: 5px;
    }

    .vh-line {
      position: absolute;
      border-left: 3px dashed #3955a5;
      left: 14px;
      top: 30px;
    }

    .vh-jbline {
      height: 93%;
    }

    .vh-wjline {
      height: 80%;
      top: 30px;
    }

    .vh-wcline {
      height: 128%;
      top: -48px;
    }

    .vh-line-yellow {
      border-color: #EF9325;
    }

    .icon-color-gray {
      background-color: rgb(151, 152, 154);
    }

    .icon-color-yellow {
      background-color: #EF9325;
    }

    .color-gray {
      color: rgb(151, 152, 154);
    }

    .color-yellow {
      color: #EF9325;
    }
  }
</style>